﻿package com.danielsheldon.GamePack
{
	import com.danielsheldon.GamePack.events.ResourceEvent;
	import flash.events.EventDispatcher;
	
	/**
	* ...
	* @author Daniel Sheldon
	*/
	public class Resource extends EventDispatcher
	{
		public var defaultDeposit:Number = 1;
		public var defaultWithdrawal:Number = 1;
		
		private var _kind:String;
		private var _balance:Number = 0;
		
		public function Resource(kind:String) 
		{
			_kind = kind;
			var rEvent:ResourceEvent = new ResourceEvent(ResourceEvent.NEW_RESOURCE, this);
			dispatchEvent(rEvent);
		}
		
		public function get kind():String
		{
			return _kind;
		}
		
		public function deposit(amount:Number = undefined):Number
		{
			if (isNaN(amount) )
			{
				_balance += defaultDeposit;
			}else {
				_balance += amount;
			}
			
			dispatchChangeEvent(ResourceEvent.RESOURCE_DEPOSIT, amount);
			
			return _balance;
		}
		
		public function withdraw(amount:Number = undefined):Number
		{
			if (isNaN(amount))
			{
				_balance -= defaultWithdrawal;
			}else {
				_balance -= amount; 
			}
			
			dispatchChangeEvent(ResourceEvent.RESOURCE_WITHDRAWAL, -amount);
			
			return _balance;
		}
		
		private function dispatchChangeEvent(type:String, amount:Number):void
		{
			
			var rEvent:ResourceEvent = new ResourceEvent(type, this);
			rEvent.change = amount;
			dispatchEvent(rEvent);
		}
		
		override public function toString():String
		{
			return "Resource[kind=" + _kind + " balance=" + _balance + " defaultDeposit=" + defaultDeposit + " defaultWithdrawal=" + defaultWithdrawal + "]"//\;
		}
		
	}
	
}